package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.enums.ItemType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.FacilityInfo;
import com.atguigu.lease.web.admin.service.FacilityInfoService;
import com.atguigu.lease.web.admin.mapper.FacilityInfoMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author gqs
 * @description 针对表【facility_info(配套信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class FacilityInfoServiceImpl extends ServiceImpl<FacilityInfoMapper, FacilityInfo>
    implements FacilityInfoService {

  @Override
  public boolean saveOrUpdateFacility(FacilityInfo facilityInfo) {
    Long id = facilityInfo.getId() == null ? -1 : facilityInfo.getId();

    FacilityInfo dbFacilityInfo =
        this.getOne(
            Wrappers.lambdaQuery(FacilityInfo.class)
                .eq(FacilityInfo::getType, facilityInfo.getType().getCode())
                .eq(FacilityInfo::getName, facilityInfo.getName())
                .last("limit 1"));

    if (dbFacilityInfo != null && !dbFacilityInfo.getId().equals(id)) {
      throw new StgyException(ResultCodeEnum.FACILITY_TYPE_EXISTS_ERROR);
    }
    return this.saveOrUpdate(facilityInfo);
  }

  @Override
  public List<FacilityInfo> listByType(ItemType type) {
    /*
       抽取业务代码：
           1、提高controller的可读性
           2、业务层方法更方便aop编程
    */
    LambdaQueryWrapper<FacilityInfo> queryWrapper = null;
    if (type != null) {
      queryWrapper =
          Wrappers.lambdaQuery(FacilityInfo.class).eq(FacilityInfo::getType, type.getCode());
    }
    return this.list(queryWrapper);
  }
}
